import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qunaimedical/components/custom_avatar.dart';
import 'package:qunaimedical/components/item_option.dart';
import 'package:qunaimedical/components/item_option_with_count.dart';
import 'package:qunaimedical/components/primary_button.dart';
import 'package:qunaimedical/components/shimmer_indicator.dart';
import 'package:qunaimedical/components/sign_button.dart';
import 'package:qunaimedical/init/provider.dart';
import 'package:qunaimedical/models/statistics.dart';
import 'package:qunaimedical/models/user.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/attendance.dart';
import 'package:qunaimedical/pages/auth.dart';
import 'package:qunaimedical/pages/favorite.dart';
import 'package:qunaimedical/pages/feedback.dart';
import 'package:qunaimedical/pages/login.dart';
import 'package:qunaimedical/pages/profile.dart';
import 'package:qunaimedical/pages/web_page.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';

class MePage extends StatefulWidget {
  @override
  _MePageState createState() => _MePageState();
}

class _MePageState extends State<MePage> {
  RefreshController _refreshController = RefreshController();

  @override
  void initState() {
    super.initState();
    CommonUtils.refreshProfile(context);
    _fetchStatistics();
  }

  @override
  Widget build(BuildContext context) {
    User user = context.watch<StoreInfo>().user;
    bool _msgSwitch = user != null && user.noDisturbing == 1;
    String authStatusText = '完善资料，奖励500积分';
    if (user != null) {
      // 1 认证成功  2 未认证  3 待认证 4 认证失败
      switch (user.authStatus) {
        case 1:
          authStatusText = '认证成功';
          break;
        case 3:
          authStatusText = '已提交资料，等待审核';
          break;
        case 4:
          authStatusText = '认证失败';
          break;
      }
    }
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            height: MediaQuery.of(context).padding.top,
            color: Color(0xff39e7ba),
          ),
          Expanded(
            child: SmartRefresher(
              controller: _refreshController,
              enablePullUp: false,
              enablePullDown: true,
              header: ShimmerHeader(
                baseColor: Color(0xff39e7ba),
                text: Text(
                  "",
                  style: TextStyle(color: Colors.grey, fontSize: 22),
                ),
              ),
              onRefresh: user == null
                  ? () => _refreshController.refreshCompleted()
                  : _refresh,
              child: ListView(
                padding: EdgeInsets.symmetric(vertical: 0),
                children: [
                  _buildHeader(context),
                  _buildDataOptions(),
                  ItemOption(
                    imagePath: 'assets/images/ic_auth.png',
                    text: '资质认证',
                    secondText: authStatusText,
                    secondTextColor: Colors.redAccent,
                    onTap: () {
                      User user = SPUtils.getUser();
                      if (user == null) {
                        _login();
                      } else {
                        if (user.authStatus == 2 || user.authStatus == 4) {
                          Navigator.pushNamed(context, AuthPage.routeName)
                              .then((value) {
                            CommonUtils.refreshProfile(context);
                          });
                        }
                      }
                    },
                  ),
                  ItemOption(
                    imagePath: 'assets/images/ic_favorite.png',
                    text: '我的收藏',
                    onTap: () {
                      if (SPUtils.getUser() == null) {
                        _login();
                      } else {
                        Navigator.pushNamed(context, FavoritePage.routeName);
                      }
                    },
                  ),
                  ItemOption(
                    imagePath: 'assets/images/ic_about.png',
                    text: '关于我们',
                    onTap: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (c) =>
                                  WebPage(url: 'http://m.belovedlive.com')));
                    },
                  ),
                  ItemOption(
                    imagePath: 'assets/images/ic_feedback.png',
                    text: '意见反馈',
                    onTap: () {
                      Navigator.push(context,
                          MaterialPageRoute(builder: (c) => FeedbackPage()));
                    },
                  ),
                  ItemOption(
                    hideRightArrow: true,
                    imagePath: 'assets/images/ic_msg.png',
                    text: '免打扰',
                    trailing: CupertinoSwitch(
                      value: _msgSwitch,
                      activeColor: Theme.of(context).primaryColor,
                      onChanged: (value) {
                        if (SPUtils.getUser() != null) {
                          setState(() {
                            _msgSwitch = value;
                          });
                          _setNoDisturbing(_msgSwitch);
                        }
                      },
                    ),
                  ),
                  Offstage(
                    offstage: user == null,
                    child: PrimaryButton(
                      '退出',
                      onPressed: () => _logout(context),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _login() {
    Navigator.pushNamed(context, LoginPage.routeName).then((value) {
      _fetchStatistics();
    });
  }

  void _logout(BuildContext context) {
    DialogUtils.showAlertDialog(context, '提示', '确认退出？', onPressed: () {
      Navigator.pop(context);
      CommonUtils.logout(context);
    });
  }

  void _setNoDisturbing(bool value) async {
    if (SPUtils.getUser() == null) {
      return;
    }
    var data = await XHttp.postJson(Urls.DOCTOR_INFO_EDIT, {
      'id': SPUtils.getUser().id,
      'noDisturbing': value ? 1 : 0,
    });
    if (data != null) {
      Map<String, dynamic> response = data as Map<String, dynamic>;
      if (response['code'] == 1) {
        User user = context.read<StoreInfo>().user;
        user.noDisturbing = value ? 1 : 0;
        context.read<StoreInfo>().updateUser(user);
      } else {
        ToastUtil.show(response['msg'], context);
      }
    }
  }

  void _refresh() async {
    await CommonUtils.refreshProfile(context);
    await _fetchStatistics();
    _refreshController.refreshCompleted();
  }

  Container _buildHeader(BuildContext context) {
    User user = context.watch<StoreInfo>().user;
    return Container(
      padding: EdgeInsets.only(
        top: 0,
        left: 16,
        right: 16,
        bottom: 0,
      ),
      height: 180,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/images/bg_header.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: Stack(
        alignment: Alignment.centerLeft,
        children: [
          Positioned(
            child: Offstage(
              offstage: user != null,
              child: InkWell(
                onTap: () {
                  _login();
                },
                child: Text(
                  '登录/注册',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
          Positioned(
            child: Offstage(
              offstage: user == null,
              child: InkWell(
                onTap: () {
                  Navigator.pushNamed(context, ProfilePage.routeName);
                },
                child: Row(
                  children: [
                    CustomAvatar(size: 80, avatarUrl: user?.avatar),
                    SizedBox(width: 10),
                    Expanded(
                      child: Text(
                        user == null
                            ? ''
                            : user.fullname != null && user.fullname.isNotEmpty
                                ? user.fullname
                                : user.username,
                        maxLines: 1,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                    )
                  ],
                ),
              ),
            ),
          ),
          Positioned(
            child: SignButton(
              onTap: () {
                if (context.read<StoreInfo>().user != null) {
                  Navigator.pushNamed(context, AttendancePage.routeName)
                      .then((value) {
                    _fetchStatistics();
                  });
                }
              },
            ),
            right: 0,
            bottom: 30,
          ),
        ],
      ),
    );
  }

  Widget _buildDataOptions() {
    Statistics statistics = context.read<StoreInfo>().statistics;
    return Container(
      transform: Matrix4.translationValues(0, -16, 0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      child: Row(children: [
        Expanded(
            child: ItemOptionWithCount(
                count: statistics.medicalCount, text: '会诊次数')),
        Expanded(
            child: ItemOptionWithCount(
                count: statistics.onlineCount, text: '问诊次数')),
        Expanded(
            child: ItemOptionWithCount(
                count: statistics.doctorIntegral, text: '积分')),
      ]),
    );
  }

  Future _fetchStatistics() async {
    if (SPUtils.getUser() == null) return;
    var data =
        await XHttp.get('${Urls.STATISTICS}?doctorId=${SPUtils.getUser().id}');
    if (data != null && mounted) {
      context.read<StoreInfo>().updateStatistics(Statistics(
            onlineCount: data['onlineCount'],
            doctorIntegral: data['doctorIntegral'],
            medicalCount: data['medicalCount'],
          ));
    }
  }
}
